package ai.people.core.web.filter.fastjson;

import ai.people.netmon.framework.annotation.Desensitized;
import ai.people.netmon.framework.businessenum.SensitiveTypeEnum;
import ai.people.netmon.utils.DesensitizationUtils;
import com.alibaba.fastjson.serializer.ValueFilter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 属性脱敏过滤器
 *
 * @author yuanqinglong
 * @date 2022/4/29 11:40
 */
@Slf4j
public class ValueDesensitizeFilter implements ValueFilter {

    @Override
    public Object process(Object object, String name, Object value) {
        if (object instanceof Map || !(value instanceof String) || ((String) value).length() == 0) {
            return value;
        }
        try {
            Field field = object.getClass().getDeclaredField(name);
            Desensitized desensitization;
            if (String.class != field.getType() || (desensitization = field.getAnnotation(Desensitized.class)) == null) {
                return value;
            }
            String valueStr = (String) value;
            SensitiveTypeEnum type = desensitization.type();
            String symbol = desensitization.symbol();
            switch (type) {
                case CHINESE_NAME:
                    return DesensitizationUtils.hiddenChineseName(valueStr);
                case ID_CARD:
                    return DesensitizationUtils.hiddenIdCard(valueStr, symbol);
                case FIXED_PHONE:
                    return DesensitizationUtils.hiddenFixedPhone(valueStr, symbol);
                case MOBILE_PHONE:
                    return DesensitizationUtils.hiddenPhone(valueStr);
                case ADDRESS:
                    return DesensitizationUtils.hiddenAddress(valueStr, 8);
                case EMAIL:
                    return DesensitizationUtils.hiddenEmail(valueStr, symbol);
                case BANK_CARD:
                    return DesensitizationUtils.hiddenBankCard(valueStr, symbol);
                case PASSWORD:
                    return DesensitizationUtils.hiddenPassword(valueStr, symbol);
                case CAR_NUMBER:
                    return DesensitizationUtils.hiddenPlateNum(valueStr, symbol);
                default:
            }
        } catch (NoSuchFieldException e) {
            log.error("当前数据类型为{},值为{}", object.getClass(), value);
            return value;
        }
        return value;
    }

}
